package com.example.permissionservice.service.impl;

import com.example.permissionservice.entity.UserRole;
import com.example.permissionservice.mapper.UserRoleMapper;
import com.example.permissionservice.service.PermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {
    private final UserRoleMapper userRoleMapper;

    private static final int ROLE_USER_ID = 2;
    private static final int ROLE_ADMIN_ID = 3;
    private static final int ROLE_SUPER_ADMIN_ID = 1;

    @Override
    @Transactional
    public void bindDefaultRole(Long userId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(ROLE_USER_ID);
        userRoleMapper.insert(userRole);
    }

    @Override
    public String getUserRoleCode(Long userId) {
        List<UserRole> userRoles = userRoleMapper.findByUserId(userId);
        if (userRoles.isEmpty()) {
            return "user";
        }
        UserRole userRole = userRoles.get(0);
        if (userRole.getRoleId() == ROLE_SUPER_ADMIN_ID) {
            return "super_admin";
        } else if (userRole.getRoleId() == ROLE_ADMIN_ID) {
            return "admin";
        } else {
            return "user";
        }
    }

    @Override
    @Transactional
    public void upgradeToAdmin(Long userId) {
        List<UserRole> userRoles = userRoleMapper.findByUserId(userId);
        if (userRoles.isEmpty()) {
            throw new RuntimeException("用户角色不存在");
        }

        UserRole userRole = userRoles.get(0);
        if (userRole.getRoleId() == ROLE_SUPER_ADMIN_ID) {
            throw new RuntimeException("超管无法被修改");
        }

        userRole.setRoleId(ROLE_ADMIN_ID);
        userRoleMapper.update(userRole);
    }

    @Override
    @Transactional
    public void downgradeToUser(Long userId) {
        List<UserRole> userRoles = userRoleMapper.findByUserId(userId);
        if (userRoles.isEmpty()) {
            throw new RuntimeException("User role not found");
        }

        UserRole userRole = userRoles.get(0);
        if (userRole.getRoleId() == ROLE_SUPER_ADMIN_ID) {
            throw new RuntimeException("Cannot downgrade super admin");
        }

        userRole.setRoleId(ROLE_USER_ID);
        userRoleMapper.update(userRole);
    }
}
